package com.tool.payment.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import com.tool.payment.PaymentConfig;
import com.tool.payment.model.PayOrder;
import com.tool.payment.model.PayParams;
import com.tool.payment.service.AbstractPaymentService;
import com.tool.payment.service.PaymentService;
import com.tool.payment.util.IdWorkerUtil;
import com.tool.payment.util.NumberUtils;
import com.tool.payment.util.alipay.AlipayNotify;
import com.tool.payment.util.alipay.AlipaySubmit;

/**
 * 支付宝支付
 * @author huff
 *
 */
@Service
public class AlipayPaymentServiceImpl extends AbstractPaymentService implements PaymentService {

	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(AlipayPaymentServiceImpl.class);
	
	
	@Override
	public Map<String, String> createOrder(String product, String mode,
			String notifyUrl, HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, String> createOrder(String notifyUrl, PayParams params,HttpServletRequest request) {
		long workid = Long.parseLong(String.valueOf(params.getWorkid()));//订单id
		int money = params.getMoney();
		long operateid = params.getUserid();
		PayOrder payOrder = new PayOrder(IdWorkerUtil.getId(),PayOrder.PAYPRODUCT_ALIPAY, PayOrder.TYPE_USERPAY, workid, money, operateid);
		payOrderService.savePayOrder(payOrder);
		String mode = params.getMode();
		logger.info("开始创建支付宝支付单:"+payOrder+"-"+request.getRemoteAddr()+"-"+mode+"-"+money);
		
		notifyUrl = params.getPreurl() + notifyUrl;
		
		PaymentConfig config = PaymentConfig.getInstance();
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", config.getAlipayPartner());
        sParaTemp.put("_input_charset", config.getAlipayInputCharset());
		sParaTemp.put("payment_type", "1");
		sParaTemp.put("notify_url", notifyUrl);
		//TODO huff 同步回调
		sParaTemp.put("return_url", params.getPreurl() + "alipay/directpay/returnurl");
		sParaTemp.put("seller_email", config.getAlipaySellerEmail());
		sParaTemp.put("out_trade_no", String.valueOf(payOrder.getId()));
		sParaTemp.put("subject", "");
		sParaTemp.put("total_fee", NumberUtils.fen2yuan(payOrder.getMoney()));
		sParaTemp.put("body", "");
		sParaTemp.put("show_url", "");
		sParaTemp.put("anti_phishing_key", "");
		sParaTemp.put("exter_invoke_ip", "");
		try {
			Map<String, String> result = new HashMap<String, String>();
			//建立请求
			String shtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
			result.put("html", shtmlText);
			return result;
		} catch (Exception e) {
			logger.info("生成支付宝订单失败：",e);
		}
		return null;
	}

	@Override
	public String payNotify(HttpServletRequest request) {
		try {
			//获取支付宝POST过来反馈信息
			Map<String,String> params = new HashMap<String,String>();
			Map requestParams = request.getParameterMap();
			boolean flag = true;
			params = this.getParams(requestParams, flag);
			flag = AlipayNotify.verify(params);
			if(!flag) {
				params = this.getParams(requestParams, flag);
				flag = AlipayNotify.verify(params);
			}
			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
			String outTradeNo = request.getParameter("out_trade_no");//商户订单号
			String tradeNo = request.getParameter("trade_no");//支付宝交易号
			String tradeStatus = request.getParameter("trade_status");//交易状态
			//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
			if(flag){//验证成功
				if(tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")){
//					this.directpay(outTradeNo, tradeNo);
					int status = PayOrder.STATUS_SUCCESS;
					PayOrder payOrder = this.updatePayOrder(outTradeNo, status, tradeNo, true);
					this.notifyService.weixinPayNotify(payOrder,status);
				} 
				return "success";	//请不要修改或删除

			}else{//验证失败
				return "fail";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}

	@Override
	public Map<String, String> refundOrder(PayParams params) {
		return null;
	}

	@Override
	public Map<String, PayOrder> reconciliation(PayParams params) {
		return null;
	}

}
